import moment from "moment/moment";
import {dateTimePattern, ossFileUrl} from "/@/main";

type amountType = '$' | '€' | '£' | '¥'
// 货币符号
export const currencySymbol: amountType = '$'

/*
 * 格式化金额
 * number：要格式化的数字
 * decimals：保留几位小数
 * decPoint：小数点符号
 * thousandsSep：千分位符号
 * roundTag:舍入参数 "ceil"向上取,"floor"向下取,"round" 四舍五入
 * */
export const formatAmount = (number: any, decimals = 2, decPoint = '.', thousandsSep = ',', roundTag = 'round') => {
    number = (number + '').replace(/[^0-9+-Ee.]/g, '')
    roundTag = roundTag || 'ceil' // "ceil","floor","round"
    var n = !isFinite(+number) ? 0 : +number
    var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
    var s = ''
    var toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec)
        return '' + parseFloat(Math[roundTag](parseFloat((n * k).toFixed(prec * 2))).toFixed(prec * 2)) / k
    }
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
    if (thousandsSep) {
        var re = /(-?\d+)(\d{3})/
        while (re.test(s[0])) {
            s[0] = s[0].replace(re, `$1${thousandsSep}$2`)
        }
    }

    if ((s[1] || '').length < prec) {
        s[1] = s[1] || ''
        s[1] += new Array(prec - s[1].length + 1).join('0')
    }
    return s.join(decPoint)
}

// console.log(formatAmount(2, 2, '.', ','))// "2.00"
// console.log(formatAmount(3.7, 2, '.', ','))// "3.70"
// console.log(formatAmount(3, 0, '.', ',')) // "3"
// console.log(formatAmount(9.0312, 2, '.', ','))// "9.03"
// console.log(formatAmount(9.00, 2, '.', ','))// "9.00"
// console.log(formatAmount(39.715001, 2, '.', ',', 'floor')) // "39.71"
// console.log(formatAmount(9.7, 2, '.', ','))// "9.70"
// console.log(formatAmount(39.7, 2, '.', ','))// "39.70"
// console.log(formatAmount(9.70001, 2, '.', ','))// "9.71"
// console.log(formatAmount(39.70001, 2, '.', ','))// "39.71"
// console.log(formatAmount(9996.03, 2, '.', ','))// "9996.03"
// console.log(formatAmount(1.797, 3, '.', ',', 'floor'))// "1.797"



/**
 * 校验金额
 * @param val
 * @param min 最小值
 * @param max 最大值
 */
export const checkAmount = (val: any, min = 1, max = 9999999) => {
    const originalVal = val
    if (!val || isNaN(val)) {
        return min ? min : 1
    }
    // 清除"数字"/"."/以外的字符
    val = val.replace(/[^\d.]/g, '')
    // 开头为小数点清除
    val = val.replace(/^\./g, '')
    // 只保留第一个.清除多余的
    val = val.replace(/\.{2,}/g, '.')
    val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
    // 只能输入三个小数
    val = val.replace(/^(-)*(\d+)\.(\d\d\d).*$/, '$1$2.$3')

    // 边界值处理
    val = parseFloat(val)
    if (min) {
        min = parseFloat(min)
        val = val < min ? min : val
    }
    if (max) {
        max = parseFloat(max)
        val = val > max ? max : val
    }
    // console.log(`checkAmount, before: ${originalVal}  after: ${val}`)
    return val
}

/**
 * 校验数字
 * @param val
 * @param min 最小值
 * @param max 最大值
 */
export const checkNumber = (val, min = 0, max = 9999999) => {
    if (!val || isNaN(val)) {
        return min ? min : 0
    }

    // 边界值处理
    val = parseInt(val)
    if (min) {
        min = parseInt(min)
        val = val < min ? min : val
    }
    if (max) {
        max = parseInt(max)
        val = val > max ? max : val
    }
    // console.log(`checkNumber: ${val}`)
    return val
}

/**
 * 校验整数
 * @param val
 */
export const checkInteger = (val: string) => {
    if (!val) {
        return val
    }
    // 清除"数字"以外的字符
    val = val.replace(/[^[0-9]/g, '')
    return val
}


// 获取文件资源地址
export const getFileUri =  (fileName: string) => {
    let url = ''
    // 如果返回的是OSS 地址则不需要增加 baseURL
    if (fileName.includes('http') || fileName.includes('/assets')) {
        url = fileName
    } else{
        url = ossFileUrl + fileName;
    }

    return url
};


// 向上保留两位小数
export const ceilFixed2 = (num: number) => {
    let ceilNum = Math.ceil(num * 100) / 100;
    return ceilNum.toFixed(2);
}



/**
 * 银行卡格式化
 * @param prefix
 * @param val
 * @param defaultVal
 * @returns {string|*}
 */
export const formatBankCard = (val: string) => {
    if (val) {
        return val.replace(/[^0-9]/g, '')
            .replace(/([0-9]{4})(?=[0-9])/g, '$1 ')
    }
    return ''
}


/**
 * 给对象赋值
 * @param target
 * @param source
 */
export const assign = (target: any, source: any) => {
    Object.assign(target, source)
}

/**
 * 给对象赋值(仅赋值目标对象有的属性)
 * @param target
 * @param source
 * @param number2str 数字类型转字符串类型
 * @param zero2empty  0转空字符串
 */
export const assignOnlyTarget = (target: { [x: string]: any; }, source: {
    [x: string]: any;
}, number2str: any, zero2empty: any) => {
    if (target && source) {
        const targetKeys = Object.keys(target)
        const sourceKeys = Object.keys(source)
        targetKeys.forEach(t => {
            sourceKeys.forEach(s => {
                if (s === t) {
                    if (number2str) {
                        target[t] = (typeof source[s] === 'number' && !isNaN(source[s])) ?
                            String(
                                zero2empty ? (source[s] === 0 ? '' : source[s]) : source[s]) :
                            source[s]
                    } else {
                        target[t] = source[s]
                    }
                }
            })
        })
    }
}




/**
 * 复制文本到粘贴板
 * @param text
 */
export const copyText = (text: { toString: () => string; }) => {
    // js创建一个input输入框
    const input = document.createElement('input')
    // 将需要复制的文本赋值到创建的input输入框中
    input.value = text.toString()
    // 将输入框暂时创建到实例里面
    document.body.appendChild(input)
    // 选中输入框中的内容
    input.select()
    // 执行复制操作
    if (document.execCommand('Copy')) {
        console.log(`copy success! val: ${text}`)
    } else {
        console.log('copy failure!')
    }
    // 最后删除实例中临时创建的input输入框，完成复制操作
    document.body.removeChild(input)
}



/**
 * 字符串转数组
 * @param str
 * @param separator
 * @returns {*|*[]}
 */
export const str2Array = (str: string, separator = '') => {
    if (!str || str === '' || str.length === 0) {
        return []
    }

    return str.split(separator)
}


/**
 * 转换单位
 * @param val               值
 * @param startUnitIndex    起始单位的下标
 * @param step              单位进制，如每1000进行转换
 * @param unit              单位数组
 * @returns {*|string}
 */
export const convertUnit = (val, startUnitIndex = 0, step = 1000, unit = ['', 'k', 'M']) => {
    if (!val || val === '' || val === null || val === undefined) {
        return 0
    }
    // 对比值
    // const compareVal = Math.abs(val)
    // // 1e3为10的三次方 1e4为10的四次方以此类推
    // if (compareVal >= 0 && compareVal < 1e3 / 2) {
    //     return val
    // } else if (compareVal >= 1e3 / 2 && compareVal < 1e4) {
    //     return
    // }

    if (Math.abs(val) >= step) {
        return convertUnit(val / step, startUnitIndex + 1, step, unit)
    }
    return `${Number(val).toFixed(1) * 100 / 100}${unit[startUnitIndex]}`
}


/**
 * 获取当前语言(没有设置则默认浏览器语言)
 * @returns {undefined}
 */
export const getCurrentLanguage = () => {
    let lang = getCookieParam('language')
    // console.log('cookie语言', lang)
    if (!lang) {
        lang = navigator.language || navigator.userLanguage
        // console.log('浏览器语言', lang)
    }
    return lang
}


/**
 * 设置当前语言
 * @returns {undefined}
 */
export const setCurrentLanguage = (val) => {
    return setCookieParam('language', val)
}

/**
 * 获取cookie中的参数
 * @param paramName
 * @returns {string}
 */
export function getCookieParam(paramName: string) {
    let paramValue = ''
    let isFound = false
    if (document.cookie.length > 0) {
        let arr = document.cookie.split(';')
        let i = 0
        while (i < arr.length && !isFound) {
            if (arr[i].indexOf(paramName) > -1) {
                isFound = true
                paramValue = arr[i].split('=')[1]
            }
            i++
        }
    }
    return paramValue
}

// 设置cookie中的参数
export function setCookieParam(paramName: string, paramValue: any) {
    let expireTime = new Date()
    // 保存30天
    expireTime.setTime(expireTime.getTime() + 30 * 24 * 60 * 60 * 1000)
    document.cookie = `${paramName}=${paramValue};expires=${expireTime.toGMTString()}`
}



/**
 * 金额格式化
 * @param amount
 * @param sign
 */
export const amountFormat = (amount: number, sign = '') => {
    let val
    if (amount || amount === 0) {
        val = `${currencySymbol}${sign}${formatAmount(amount)}`
    } else {
        val = '-'
    }
    // console.log(`origin val: ${amount} -> format val: ${val}, typeof: ${typeof val}, sign: ${sign}`)
    return val
}

// 状态格式化
export const stateFormat = (
    val: any,
    list: Array<any> = [],
    prop: object = { value: 'value', label: 'text' }
) => {
    if (val === undefined || val === null || val === '') {
        return ''
    }

    const find = (list || []).find((item) => Number(item[prop.value]) == Number(val))
    return find ? find[prop.label] : ''
}

// 语言格式化
export const langFormat = (val: object) => {
    if (val === null || val === undefined) {
        return ''
    }
    let lang = getCurrentLanguage()
    console.log('langFormat', val, lang)
    return lang ? val[lang.toLowerCase()] : val.en
}

// 清空前后空格
export const trim = (val: string) => {
    return val.replace(/(^\s*)|(\s*$)/g, '')
}

// 距离格式化
export const distanceFormat = (val: any) => {
    console.log('distanceFormat', val)
    if (val) {
        val = Number(val)
        if (val < 1000) {
            return val.toFixed() + 'm'
        } else {
            return (val / 1000).toFixed(2) + 'km'
        }
    } else {
        return ''
    }
}

// 连接格式化
export const joinFormat = (separate: any = '/', ...val: any[]) => {
    let res = ''
    val.forEach((item, index) => {
        res += item ? `${item}${index != val.length - 1 ? separate : ''}` : ''
    })
    // 处理最后一个元素为空的情况
    if (res.lastIndexOf(separate) == res.length - 1) {
        res = res.substring(0, res.length - 1)
    }
    // console.log('连接格式化', res, val)
    return res
}


// 日期格式化
export const dateformat = (val: moment.MomentInput, pattern = dateTimePattern) => {
    return val ? moment(val).format(pattern) : ''
}

// 日期范围格式化
export const dateRangeFormat = (start: moment.MomentInput, end: moment.MomentInput, pattern = dateTimePattern) => {
    if (start && end) {
        return `${moment(start).format(pattern)} ~ ${moment(end).format(pattern)}`
    } else {
        return ''
    }
}

// 名称+电话格式化
export const nameMobileFormat = (val: any, mobile: any) => {
    if (val && mobile) {
        return `${val}(${mobile})`
    } else if (val) {
        return val
    } else if (mobile) {
        return mobile
    } else {
        return ''
    }
}



// 打开链接
export const openUrl = (url: string | URL | undefined, target: string | undefined) => {
    window.open(url, target);
};

/**
 * 计算百分比
 * @param val       分子
 * @param total     分母
 * @param decimal   保留几位小数
 */
export const calcPercentage = (val, total, decimal = 1) => {
    if (!(val && total)) {
        return 0
    }
    if (total === 0 || val === 0) {
        return 0
    }
    return Number((val / total * 100).toFixed(decimal))
}



// 类型-图片
export const typeImage = ['gif', 'png', 'jpg', 'jpeg', 'webp', 'svg', 'psd', 'bmp', 'tif']
// 类型-视频
export const typeVideo = ['swf', 'avi', 'flv', 'mpg', 'rm', 'mov', 'wav', 'asf', '3gp', 'mkv', 'rmvb', 'mp4'];

// 判断是否是图片
export const isImage = (url: string) => {
    return typeImage.includes(url.split('.').pop()!.toLowerCase());
}
// 判断是否是视频
export const isVideo = (url: string) => {
    return typeVideo.includes(url.split('.').pop()!.toLowerCase());
}

/**
 * 查看大图
 * @param url
 */
export const viewLargeImg = (url: string) => {
    const extension = url.split('.').pop()!.toLowerCase() ;
    let pattern;
    // 根据文件扩展名判断是图片还是视频
    if (typeImage.includes(extension )) {
        // 图片文件，移除后缀中的 "_[数字]" 或 "_thumb"
        pattern = new RegExp(`(_\\d+|_thumb)\\.(${typeImage.join('|')})$`, 'i');
    } else if (typeVideo.includes(extension)) {
        // 视频文件，移除后缀中的 "_compress"
        pattern = new RegExp(`(_compress)\\.(${typeVideo.join('|')})$`, 'i');
    } else {
        // 如果不是图片或视频，不做处理直接返回原URL
        return url;
    }

    // 替换匹配到的模式为相应的扩展名，即删除特定的后缀
    return url.replace(pattern, '.$2');

    // 示例用法
    // let imageUrl = "http://example.com/path/image_1024.jpg";
    // let imageUrl2 = "https://sanyanhu.oss-cn-shenzhen.aliyuncs.com/uploads/20240504/images/98d4d5fd1cb6c8ffc6236742e5251c17/original_375.jpg";
    // let videoUrl = "http://example.com/videos/video_compress.mp4";
    //
    // console.log(viewLargeImg(imageUrl));  // 输出: http://example.com/path/image.jpg
    // console.log(viewLargeImg(imageUrl2));  // 输出: https://sanyanhu.oss-cn-shenzhen.aliyuncs.com/uploads/20240504/images/98d4d5fd1cb6c8ffc6236742e5251c17/original.jpg
    // console.log(viewLargeImg(videoUrl));  // 输出: http://example.com/videos/video.mp4
};




